package com.example.doctorsystem.service.impl;

import com.example.doctorsystem.dao.DoctorDao;
import com.example.doctorsystem.dao.MedicineDao;
import com.example.doctorsystem.dao.PatientDao;
import com.example.doctorsystem.dao.PrescriptionDao;
import com.example.doctorsystem.model.Doctor;
import com.example.doctorsystem.model.Medicine;
import com.example.doctorsystem.model.Patient;
import com.example.doctorsystem.model.Prescription;
import com.example.doctorsystem.service.PrescriptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PrescriptionServiceImpl implements PrescriptionService {

    @Autowired
    private PrescriptionDao prescriptionDao;

    @Autowired
    private DoctorDao doctorDao;

    @Autowired
    private PatientDao patientDao;

    @Autowired
    private MedicineDao medicineDao;

    @Override
    public int createPrescription(Prescription p) {
        Doctor doctor = doctorDao.getDoctorById(p.getDoctorId());
        if (doctor == null) throw new IllegalArgumentException("医生不存在");
        Patient patient = patientDao.getPatientById(p.getPatientId());
        if (patient == null) throw new IllegalArgumentException("患者不存在");
        Medicine medicine = medicineDao.getMedicineByName(p.getMedicineName());
        if (medicine == null) throw new IllegalArgumentException("药品不存在");
        if (medicine.getQuantity() < p.getAmount())
            throw new IllegalArgumentException("库存不足");

        p.setDoctorName(doctor.getName());
        p.setPatientName(patient.getName());

        medicineDao.updateQuantity(medicine.getId(), medicine.getQuantity() - p.getAmount());

        return prescriptionDao.createPrescription(p);
    }

    @Override
    public List<Prescription> getPrescriptionsByDoctorId(int doctorId) {
        return prescriptionDao.getPrescriptionsByDoctorId(doctorId);
    }

    @Override
    public List<Prescription> getPrescriptionsByPatientId(int patientId) {
        return prescriptionDao.getPrescriptionsByPatientId(patientId);
    }

    @Override
    public List<Prescription> getAllPrescriptions() {
        return prescriptionDao.getAllPrescriptions();
    }

    @Override
    public boolean deletePrescription(int id) {
        Prescription p = prescriptionDao.getById(id);
        if (p == null) throw new IllegalArgumentException("处方不存在");

        Medicine medicine = medicineDao.getMedicineByName(p.getMedicineName());
        if (medicine != null) {
            medicineDao.updateQuantity(medicine.getId(), medicine.getQuantity() + p.getAmount());
        }

        return prescriptionDao.deletePrescription(id) > 0;
    }
}
